package com.wjm.defusecamera;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class MainActivity extends AppCompatActivity {

    private Context TAG;
    private String LOG_TAG = "LOG_TAG";

    private int request_code_flag;//当前的业务类型
    private int REQUEST_CODE_ONE_CAMERA = 101;
    private int REQUEST_CODE_TWO_CAMERA = 102;
    private int VIDEO_noOutPath_REQUEST_CODE = 201;
    private int VIDEO_setOutPath_REQUEST_CODE = 202;
    //    private static final String FILE_PATH = "/sdcard/sysvideocamera.3gp";
    private static final String FILE_PATH = "mnt/sdcard/wjm/in720 31.mp4";//"mnt/sdcard/wjm/spring-2.5.rar";
    private TextView tv_def_use_camera;
    private TextView tv_def_use_camera_video;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_def_use_camera = findViewById(R.id.tv_def_use_camera);
        tv_def_use_camera_video = findViewById(R.id.tv_def_use_camera_video);
        TAG = MainActivity.this;
        tv_def_use_camera.setText(error1);
        tv_def_use_camera_video.setText(error2);
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_def_use_camera) {
            request_code_flag= REQUEST_CODE_ONE_CAMERA;
            MainActivityPermissionsDispatcher.NeedsPermission_One_CameraWithPermissionCheck(this);
//            //要权限,要相机权限
//            defUedCamera_One(MainActivity.this);
        } else if (id == R.id.btn_def_use_camera_EXTRA_OUTPUT) {//拍照指定保存位置-

            MainActivityPermissionsDispatcher.NeedsPermission_Two_CameraWithPermissionCheck(this);
            request_code_flag= REQUEST_CODE_TWO_CAMERA;

//            defUedCamera_Two_Set_Extra_output(this);
        } else if (id == R.id.btn_def_use_camera_video) {//摄像不指定保存位置-
//            MainActivityPermissionsDispatcher.needsPermission3WithPermissionCheck(this);

            request_code_flag= VIDEO_noOutPath_REQUEST_CODE;
            MainActivityPermissionsDispatcher.NeedsPermission_One_CameraWithPermissionCheck(this);

//            //要权限,要相机权限
//            testActionVideoCapture();
        } else if (id == R.id.btn_def_use_camera_video_EXTRA_OUTPUT) {//摄像指定保存位置-
//            action_video_capture_extra_output(this);

            request_code_flag= VIDEO_setOutPath_REQUEST_CODE;
            MainActivityPermissionsDispatcher.NeedsPermission_Two_CameraWithPermissionCheck(this);
        }
    }

    /**
     * 参考：http://www.cnblogs.com/over140/archive/2011/11/16/2251344.html
     */
    private void action_video_capture_extra_output(Context context) {//摄像指定保存位置-
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//参数设置可以省略MediaStore.EXTRA_VIDEO_QUALITY- 此值在最低质量最小文件尺寸时是0，在最高质量最大文件尺寸时是１.

//        File videoFile = createVideoFile(context);
//        if (videoFile != null) {
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));//指定输出目录，但要先创建这个文件
//        }

        photoFile = getOutputMediaFile();
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", photoFile);
        } else {
            fileUri = Uri.fromFile(photoFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);//指定输出目录，但要先创建这个文件

        startActivityForResult(intent, VIDEO_setOutPath_REQUEST_CODE);
    }
//
//    private File createVideoFile(Context context) {
//        String scVedio1 = "scVedio.mp4";//
////        String scVedio1 = "生产视频1.mp4";//
//        String path = "mnt/sdcard/wjm/" + scVedio1;
//        File file = new File(path);
//        if (!file.exists()) {
//            file.mkdirs();
//            try {
//                file.createNewFile();
//                Toast.makeText(this, "创建文件" + file.getAbsolutePath().toString() + "成功", Toast.LENGTH_SHORT).show();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return file;
//    }

    //相机----摄像不指定保存位置----要-----------------------------------------3个---------------------------------------权限
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    public void needsPermission3() {
        Toast.makeText(this, "摄像3个权限还真拿到了-needsPermission3", Toast.LENGTH_SHORT).show();
        testActionVideoCapture();
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    void onShowRationale3(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("没给权限大哥。。。onShowRationale3")
                .setPositiveButton("好的，现在申请", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    void onPermissionDenied3() {
        Toast.makeText(this, "没权限怎么玩onPermissionDenied3", Toast.LENGTH_SHORT).show();

    }


    private AlertDialog alertDialog3;

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    void onNeverAskAgain3() {
        alertDialog3 = new AlertDialog.Builder(this)
                .setMessage("竞敢不给权限。。。，请手动去设置中开启权限onNeverAskAgain3")
                .setPositiveButton("去手动开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PermissionUtils.startSettActivity(MainActivity.this);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog3.dismiss();
                    }
                }).create();
        alertDialog3.show();
    }
    //相机----摄像不指定保存位置----要-----------------------------------------3个---------------------------------------权限


    //相机----拍照不指定保存位置-----要--------------------------1个------------------------------权限
    @NeedsPermission({Manifest.permission.CAMERA})
    public void NeedsPermission_One_Camera() {
        if(request_code_flag== REQUEST_CODE_ONE_CAMERA){

            defUedCamera_One(MainActivity.this);//拍照不指定保存位置-只要1个权限

        }else if(request_code_flag== VIDEO_noOutPath_REQUEST_CODE){//摄像不指定保存位置-只要1个权限

            testActionVideoCapture();

        }
        Toast.makeText(this, "NeedsPermission_One_Camera-有权限", Toast.LENGTH_SHORT).show();
    }

    @OnShowRationale({Manifest.permission.CAMERA})
    void OnShowRationale_One_Camera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("OnShowRationale_One_Camera-没给权限大哥。。。")
                .setPositiveButton("好的，现在申请", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void OnPermissionDenied_One_Camera() {
        Toast.makeText(this, "OnPermissionDenied_One_Camera-没权限怎么玩", Toast.LENGTH_SHORT).show();
    }

    private AlertDialog alertDialog;

    @OnNeverAskAgain({Manifest.permission.CAMERA})
    void OnNeverAskAgain_One_Camera() {
        alertDialog = new AlertDialog.Builder(this)
                .setMessage("OnNeverAskAgain_One_Camera-竞敢不给权限。。。，请手动去设置中开启权限")
                .setPositiveButton("去手动开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PermissionUtils.startSettActivity(MainActivity.this);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
    //相机----拍照不指定保存位置-----要--------------------------1个------------------------------权限

    //相机---拍照指定保存位置--------要--------------------------2个------------------------------权限 ？？？要2个权限，要sdcard权限
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    public void NeedsPermission_Two_Camera() {
        if(request_code_flag==REQUEST_CODE_TWO_CAMERA){//拍照指定保存位置-要1个权限
            defUedCamera_Two_Set_Extra_output(MainActivity.this);
        }else if(request_code_flag== VIDEO_setOutPath_REQUEST_CODE){//摄像指定保存位置-要2个权限-VIDEO_setOutPath_REQUEST_CODE
            action_video_capture_extra_output(this);

        }
        Toast.makeText(this, "NeedsPermission_Two_Camera-有权限", Toast.LENGTH_SHORT).show();

    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void OnShowRationale_Two_Camera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("OnShowRationale_Two_Camera-没给权限大哥。。。")
                .setPositiveButton("好的，现在申请", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void OnPermissionDenied_Two_Camera() {
        Toast.makeText(this, "OnPermissionDenied_Two_Camera-没权限怎么玩", Toast.LENGTH_SHORT).show();
    }


    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void OnNeverAskAgain_Two_Camera() {
        alertDialog = new AlertDialog.Builder(this)
                .setMessage("OnNeverAskAgain_Two_Camera-竞敢不给权限。。。，请手动去设置中开启权限")
                .setPositiveButton("去手动开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PermissionUtils.startSettActivity(MainActivity.this);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }
    //相机---拍照指定保存位置--------要--------------------------2个------------------------------权限 ？？？要2个权限，要sdcard权限

    //使用permissionsdispatcher框架此方法必写
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    /**
     * 原生相机使用
     * 参考：http://www.cnblogs.com/vir56k/archive/2012/10/24/2737119.html
     *
     * @param context
     */
    private void defUedCamera_One(Context context) {//拍照不指定保存位置-
/*        //向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一个数据，那么返回标识ID。
        //在完成拍照后，新的照片会以此处的photoUri命名. 其实就是指定了个文件名
        ContentValues values = new ContentValues();
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //准备intent，并 指定 新 照片 的文件名（photoUri）
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
        //启动拍照的窗体。并注册 回调处理。
        startActivityForResult(intent, REQUEST_CODE_TWO_CAMERA);*/

        // 创建拍照Intent并将控制权返回给调用的程序

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 启动图像捕获Intent
        startActivityForResult(intent, REQUEST_CODE_ONE_CAMERA);
    }

    /**
     * 原生相机使用
     * 参考：http://www.cnblogs.com/vir56k/archive/2012/10/24/2737119.html
     *
     * @param context
     */
    private void defUedCamera_Two_Set_Extra_output(Context context) {//拍照指定保存位置
/*        //向  MediaStore.Images.Media.EXTERNAL_CONTENT_URI 插入一个数据，那么返回标识ID。
        //在完成拍照后，新的照片会以此处的photoUri命名. 其实就是指定了个文件名
        ContentValues values = new ContentValues();
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        //准备intent，并 指定 新 照片 的文件名（photoUri）
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
        //启动拍照的窗体。并注册 回调处理。
        startActivityForResult(intent, REQUEST_CODE_TWO_CAMERA);*/

        // 创建拍照Intent并将控制权返回给调用的程序

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


        photoFile = getOutputMediaFile();
        Uri fileUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".FileProvider", photoFile);
        } else {
            fileUri = Uri.fromFile(photoFile);
        }

// 创建保存图片的文件
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// 设置图片文件名
        // 启动图像捕获Intent
        startActivityForResult(intent, REQUEST_CODE_TWO_CAMERA);
    }

    private File photoFile;


    /**
     * 为保存图片或视频创建文件Uri
     */

    private Uri getOutputMediaFileUri() {
        return Uri.fromFile(getOutputMediaFile());
    }

    /**
     * 放在wjm文件夹中
     *
     * @return
     */
    private File getOutputMediaFile() {
        // 安全起见，在使用前应该
        // 用Environment.getExternalStorageState()检查SD卡是否已装入
//        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "wjm");///storage/emulated/0/Pictures/wjm/IMG_20180706_165453.jpg
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "wjm");//
// 如果期望图片在应用程序卸载后还存在、且能被其它应用程序共享，
// 则此保存位置最合适
        // 如果不存在的话，则创建存储目录
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(LOG_TAG, "failed to create directory");
                return null;
            }
        }
        // 创建媒体文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;

        if (request_code_flag == REQUEST_CODE_TWO_CAMERA){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "IMG_"+ timeStamp + ".jpg");
        } else if(request_code_flag == VIDEO_setOutPath_REQUEST_CODE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }

    /**
     * 参考：http://www.cnblogs.com/over140/archive/2011/11/16/2251344.html
     */
    private void testActionVideoCapture() {
/*        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);//ACTION_VIDEO_CAPTURE
//        intent.setAction("android.media.action.VIDEO_CAPTURE");//ACTION_VIDEO_CAPTURE
        intent.addCategory("android.intent.category.DEFAULT");
        if(null!=FILE_PATH){

        }
        File photoFile = new File(FILE_PATH);
        if (photoFile.exists()) {
            photoFile.delete();
        }
        Uri uri = Uri.fromFile(photoFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, VIDEO_noOutPath_REQUEST_CODE);*/

        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//参数设置可以省略MediaStore.EXTRA_VIDEO_QUALITY- 此值在最低质量最小文件尺寸时是0，在最高质量最大文件尺寸时是１.
//        int size=10;//10M? EXTRA_VIDEO_QUALITY=0 测试5秒194KB 超模糊
//        int size=100;//100M? EXTRA_VIDEO_QUALITY=0 测试5秒529KB(542612)  EXTRA_VIDEO_QUALITY=1 5秒27.08MB(28392610)
//        int size=10;//10M? EXTRA_VIDEO_QUALITY=1 测试5秒？MB(？) 注意，这个属性有用，设置10M后，录制2秒自动结束了录制，并提示“已达到大小上限”，再看文件大小还真是10M以内,666...
//        int size=200;//200M? EXTRA_VIDEO_QUALITY=1
//        if (size != 0) {
//            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, size * 1024 * 1024L);//限制录制大小(10M=10 * 1024 * 1024L) 大小限制是long型，int 型无效，所以后边要写一个L，即1024*1024L，1MB的限制
//        }
//        int limit_time=10;//(10秒=10) 测试限制录制时长最大10秒,我靠真有用，点了录制按钮后，上面时间是倒数的，10-0，然后视频自动结束了,文件大小 是43.39MB
//        int limit_time=60*2;// 2分钟
//        if (limit_time != 0) {
//            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, limit_time);//限制录制时间(10秒=10)
//        }
//        File videoFile = createVideoFile(context);
//        if (videoFile != null) {
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));//指定输出目录，但要先创建这个文件
//        }
        startActivityForResult(intent, VIDEO_noOutPath_REQUEST_CODE);
    }
    String error1="-不知道图片路径？ -拍照不指定保存位置-有问题-待解决-???";
    String error2="-？？？-问题-待解决-111-指定摄像位置后按默认保存的位置取数据cursor报错CursorIndexOutOfBoundsException";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(LOG_TAG, "requestCode" + requestCode + "resultCode" + resultCode + "data" + data);

        if (requestCode == REQUEST_CODE_ONE_CAMERA) {//图片保存在默认位置,不知道图片路径？ -拍照不指定保存位置-有问题-待解决-???
            if (resultCode == RESULT_OK) {
                // 捕获的图像保存到Intent指定的fileUri
                if (null != data) {
                    Uri uri = data.getData();
                    Bundle extras = data.getExtras();
                    if (null != extras) {
                        if (data.hasExtra("data")) {

                            Object obj = extras.get("data");

                            //处理缩略图
                            Bitmap bit = (Bitmap) extras.get("data");
                            Bitmap bit2 = data.getParcelableExtra("data");
                            Log.d(LOG_TAG, "test");

                            Toast.makeText(this,error1,Toast.LENGTH_SHORT).show();
                            tv_def_use_camera.setText(error2);
                        }

                    }
                    //                if (null != photoFile) {
//                    String photoPath = photoFile.getAbsolutePath();///storage/emulated/0/wjm/IMG_20180706_171356.jpg
//                    if(null!=photoPath){
//                        String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(photoPath);
//                        tv_def_use_camera.setText("拍摄的照片路径：" + photoPath + "\n文件大小：" + autoFileOrFilesSize);
//                    }
//                    Log.i(LOG_TAG, "" + photoPath);
//                }
                }
            } else if (resultCode == RESULT_CANCELED) {
                // 用户取消了图像捕获
            } else {
                // 图像捕获失败，提示用户
            }
        } else if (requestCode == REQUEST_CODE_TWO_CAMERA) {//拍照指定保存位置-
            if (resultCode == RESULT_OK) {
                // 捕获的图像保存到Intent指定的fileUri
                if (null != photoFile) {
                    String photoPath = photoFile.getAbsolutePath();///storage/emulated/0/wjm/IMG_20180706_171356.jpg
                    if (null != photoPath) {
                        String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(photoPath);
                        tv_def_use_camera.setText("拍摄的照片路径：" + photoPath + "\n文件大小：" + autoFileOrFilesSize);
                    }
                    Log.i(LOG_TAG, "" + photoPath);
                }
            } else if (resultCode == RESULT_CANCELED) {
                // 用户取消了图像捕获
            } else {
                // 图像捕获失败，提示用户
            }


        } else if (requestCode == VIDEO_noOutPath_REQUEST_CODE) {//摄像不指定保存位置-
            if (resultCode == RESULT_OK) {
                // 捕获的图像保存到Intent指定的fileUri
                if (null != data) {
                    Uri videoUri = data.getData();//content://media/external/video/media/873126
//String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE };
                    Cursor cursor = managedQuery(videoUri, null, null, null, null);
                    cursor.moveToFirst();//这个必须加，否则下面读取会报错
                    int num = cursor.getCount();//1
                    String recordedVideoFilePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));///storage/emulated/0/DCIM/Camera/VID_20180706_133615.mp4  /storage/emulated/0/DCIM/Camera/VID_20180706_192345.mp4
                    int recordedVideoFileSize = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));//27140114=25.88MB(5秒)(25*12*5=1500)
//                    tv_def_use_camera_video.setText("拍摄的视频路径：" + recordedVideoFilePath + "\n文件大小：" + recordedVideoFileSize);
                    String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(recordedVideoFilePath);//10.30MB 10799957
                    tv_def_use_camera_video.setText("拍摄的视频路径：" + recordedVideoFilePath + "\n文件大小：" + autoFileOrFilesSize);
                    Log.i(LOG_TAG, "" + recordedVideoFileSize);
                }
            } else if (resultCode == RESULT_CANCELED) {
                // 用户取消了图像捕获
            } else {
                // 图像捕获失败，提示用户
            }


        }else if (requestCode == VIDEO_setOutPath_REQUEST_CODE) {//摄像指定保存位置-
            if (resultCode == RESULT_OK) {
//                // 捕获的图像保存到Intent指定的fileUri
//                if (null != data) {
//                    Uri videoUri = data.getData();//content://media/external/video/media/873126
////String[] projection = { MediaStore.Video.Media.DATA, MediaStore.Video.Media.SIZE };
//                    Cursor cursor = managedQuery(videoUri, null, null, null, null);
//                    cursor.moveToFirst();//这个必须加，否则下面读取会报错
//                    int num = cursor.getCount();//1
//                    String recordedVideoFilePath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));///storage/emulated/0/DCIM/Camera/VID_20180706_133615.mp4  /storage/emulated/0/DCIM/Camera/VID_20180706_192345.mp4
//                    int recordedVideoFileSize = cursor.getInt(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));//27140114=25.88MB(5秒)(25*12*5=1500)
////                    tv_def_use_camera_video.setText("拍摄的视频路径：" + recordedVideoFilePath + "\n文件大小：" + recordedVideoFileSize);
//                    String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(recordedVideoFilePath);//10.30MB 10799957
//                    tv_def_use_camera_video.setText("拍摄的视频路径：" + recordedVideoFilePath + "\n文件大小：" + autoFileOrFilesSize);
//                    Log.i(LOG_TAG, "" + recordedVideoFileSize);
//                }


                Toast.makeText(this,error2,Toast.LENGTH_SHORT).show();
                //-？？？-问题-待解决-111-指定摄像位置后按默认保存的位置取数据cursor报错CursorIndexOutOfBoundsException
                if (null != photoFile) {
                    String photoPath = photoFile.getAbsolutePath();///storage/emulated/0/wjm/IMG_20180706_171356.jpg
                    if (null != photoPath) {
                        String autoFileOrFilesSize = FileSizeUtil.getAutoFileOrFilesSize(photoPath);
                        tv_def_use_camera_video.setText("拍摄的照片路径：" + photoPath + "\n文件大小：" + autoFileOrFilesSize+"\n"+error2);
                    }
                    Log.i(LOG_TAG, "" + photoPath);
                }

            } else if (resultCode == RESULT_CANCELED) {
                // 用户取消了图像捕获
            } else {
                // 图像捕获失败，提示用户
            }


        }
    }
}
/*
调用系统拍5秒25MB
        /storage/emulated/0/DCIM/Camera/VID_20180706_133615.mp4
        27140114=25.88MB(5秒)(25*12*5=1500)

        自已去使用相机的拍5秒只有9MB VID_20180706_134339.mp4(格式为mp4)
        什么鬼

        EXTRA_VIDEO_QUALITY设置为0，拍5秒只有529KB,视频不清楚此属性不能用(格式为3gp)

        int size=10;//10M?
        if (size != 0) {
            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, size * 1024 * 1024L);//限制录制大小(10M=10 * 1024 * 1024L)设置10后，注意EXTRA_VIDEO_QUALITY要设置为1，不然还是很小因为格式为3gp，EXTRA_VIDEO_QUALITY设置为1后视频格式就是mp4了,文件大小27.08MB(28392610)
        }

        //大小时长没必要限制，关键是清楚度
        不限制拍30秒157MB
        60=314
        120=628
        60*5=1570
*/
//requestCode = 100
//        resultCode = 0
//        Intent {  }

//requestCode = 100
//        resultCode = -1
//        Intent { dat=content://media/external/video/media/873125 flg=0x1 }

//    Caused by: java.lang.reflect.InvocationTargetException
//        at java.lang.reflect.Method.invoke(Native Method)
//        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
//        at android.view.View.performClick(View.java:5619) 
//        at android.view.View$PerformClick.run(View.java:22295) 
//        at android.os.Handler.handleCallback(Handler.java:754) 
//        at android.os.Handler.dispatchMessage(Handler.java:95) 
//        at android.os.Looper.loop(Looper.java:163) 
//        at android.app.ActivityThread.main(ActivityThread.java:6337) 
//        at java.lang.reflect.Method.invoke(Native Method) 
//        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 
//        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) 
//        Caused by: android.os.FileUriExposedException: photoFile:///mnt/sdcard/wjm/%E7%94%9F%E4%BA%A7%E8%A7%86%E9%A2%911.mp4 exposed beyond app through ClipData.Item.getUri()
//        at android.os.StrictMode.onFileUriExposed(StrictMode.java:1799)
/*
指定位置摄像后，返回时按不指定位置取数据报如下错
 Process: com.wjm.defusecamera, PID: 29442
         java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=201, result=-1, data=Intent { dat=content://com.wjm.defusecamera.FileProvider/external_storage_root/wjm/VID_20180706_194800.mp4 flg=0x1 }} to activity {com.wjm.defusecamera/com.wjm.defusecamera.MainActivity}: android.database.CursorIndexOutOfBoundsException: Requested column: -1, # of columns: 2
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4173)
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:4216)
         at android.app.ActivityThread.-wrap20(ActivityThread.java)
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1590)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:163)
         at android.app.ActivityThread.main(ActivityThread.java:6337)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
         Caused by: android.database.CursorIndexOutOfBoundsException: Requested column: -1, # of columns: 2
         at android.database.MatrixCursor.get(MatrixCursor.java:66)
         at android.database.MatrixCursor.getString(MatrixCursor.java:254)
         at android.database.CursorWrapper.getString(CursorWrapper.java:137)
         at com.wjm.defusecamera.MainActivity.onActivityResult(MainActivity.java:531)
         at android.app.Activity.dispatchActivityResult(Activity.java:7122)
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4169)
         at android.app.ActivityThread.handleSendResult(ActivityThread.java:4216) 
         at android.app.ActivityThread.-wrap20(ActivityThread.java) 
         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1590) 
         at android.os.Handler.dispatchMessage(Handler.java:102) 
         at android.os.Looper.loop(Looper.java:163) 
         at android.app.ActivityThread.main(ActivityThread.java:6337) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770) */
